import axios, {
  InternalAxiosRequestConfig,
  AxiosResponse,
  AxiosError,
} from '@ohos/axios';
const chufa = axios.create({
  baseURL: 'https://open.bigmodel.cn/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Bearer 28d3397befca4ff5b864015cd43e1466.AGzDB93tmhnS2jxQ',
  },
});

// 生成图片：明确返回结构（异步返回id，同步返回data）
async function generateImage(title: string) {
  try {
    console.log("正在提交图像生成任务...");
    const response = await chufa.post('/paas/v4/images/generations', {
      model: "cogview-3-flash",
      prompt: title,
      user_id: "user123456",
      n: 1
    });

    // 异步任务（返回id）
    if (response.data.id) {
      console.log('图片任务ID:', response.data.id);
      return { id: response.data.id };
    }
    // 同步任务（直接返回图片数据）
    else if (response.data.data && response.data.data.length > 0) {
      console.log("✅ 图像生成成功!", JSON.stringify(response.data));
      return { data: response.data.data };
    }
    // 异常情况
    else {
      console.log("❌ 图像生成失败: 返回数据格式不正确");
      return null;
    }
  } catch (error) {
    console.error("❌ 调用失败:", error.response?.data || error.message);
    return null;
  }
}
// 轮询时正确映射封面（图片复用URL）
async function getImageResult(taskId: string): Promise<MediaResultItem[] | null> {
  try {
    const res: AxiosResponse<ImageResultResponse> = await chufa.get(`/paas/v4/async-result/${taskId}`);
    if (res.data.task_status === 'SUCCESS' && res.data.image_result) {
      return res.data.image_result.map(item => ({
        url: item.url,
        cover_image_url: item.url, // 图片无封面，复用URL
      }));
    }
    return null;
  } catch (error) {
    const axiosError = error as AxiosError;
    // 打印完整错误响应（关键！）
    console.error('查询图片失败:', {
      status: axiosError.response?.status,
      data: axiosError.response?.data, // API返回的具体错误原因
      message: axiosError.message
    });
    throw error;
  }
}
// 轮询图片结果（同视频逻辑）
async function pollImageResult(taskId: string, maxAttempts = 30): Promise<MediaResultItem[] | null> {
  for (let i = 1; i <= maxAttempts; i++) {
    const result = await getImageResult(taskId);
    if (result) return result;
    if (i < maxAttempts) await new Promise(resolve => setTimeout(resolve, 10000));
  }
  return null;
}

// 完整图片生成流程
export async function testImageGeneration(prompt: string): Promise<MediaResultItem[] | null> {
  const generationResult = await generateImage(prompt);
  if (!generationResult) {
    return null;
  }
  // 如果是异步接口（返回id），则轮询；否则直接返回图片数据
  if (generationResult.id) {
    return await pollImageResult(generationResult.id);
  } else if (generationResult.data) {
    // 同步接口，直接映射为MediaResultItem
    return generationResult.data.map(item => ({ url:item.url, cover_image_url: item.url }));
  }
  return null;
}
async function generateVideo(prompt = '') {
  try {
    const res = await chufa.post('/paas/v4/videos/generations', {
      model: 'cogvideox-flash',
      prompt: prompt,
      user_id: '40351753789750035',
    });
    console.log('视频生成任务已提交，任务ID:', JSON.stringify(res.data.id));
    return res.data;
  } catch (error) {
    console.error(
      '生成视频失败:',
      JSON.stringify(error.response?.data || error.message)
    );
    throw error;
  }
}

// 查询视频结果
async function getVideoResult(taskId): Promise<VideoResultItem[] | null> {
  try {
    const res = await chufa.get(`/paas/v4/async-result/${taskId}`);

    console.log('任务状态:', JSON.stringify(res.data.task_status));

    // 检查任务状态
    if (res.data && res.data.task_status) {
      if (res.data.task_status === 'SUCCESS' && res.data.video_result) {
        console.log('✅ 视频生成完成！');
        console.log(JSON.stringify(res));
        return res.data.video_result;
      } else if (res.data.task_status === 'FAILED') {
        console.log('❌ 任务失败:', JSON.stringify(res.data));
        return null;
      } else {
        console.log('⏳ 任务还在处理中...');
        return null;
      }
    } else {
      console.log('❓ 无法获取任务状态');
      return null;
    }
  } catch (error) {
    console.error(
      '查询视频失败:',
      JSON.stringify(error.response?.data || error.message)
    );
    throw error;
  }
}

// 轮询查询视频结果
async function pollVideoResult(
  taskId,
  maxAttempts = 30
): Promise<VideoResultItem[] | null> {
  console.log(`开始轮询任务 ${taskId}，最多 ${maxAttempts} 次...`);

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    console.log(`\n第 ${attempt} 次查询...`);

    try {
      const result = await getVideoResult(taskId);
      if (result) {
        console.log('🎉 视频生成成功！');
        console.log('视频URL:', JSON.stringify(result[0].url));
        console.log('封面URL:', JSON.stringify(result[0].cover_image_url));
        return result;
      }

      if (attempt < maxAttempts) {
        console.log('⏰ 等待 10 秒后重试...');
        await new Promise(resolve => setTimeout(resolve, 10000));
      }
    } catch (error) {
      console.error(
        `❌ 第 ${attempt} 次查询失败:`,
        JSON.stringify(error.message)
      );
      if (attempt < maxAttempts) {
        await new Promise(resolve => setTimeout(resolve, 10000));
      }
    }
  }

  console.log('⏰ 达到最大查询次数，视频可能还在生成中');
  return null;
}

async function generateVideoComplete(
  prompt = ''
): Promise<VideoResultItem[] | null> {
  try {
    console.log('🚀 开始生成视频...');
    console.log('📝 提示词:', JSON.stringify(prompt));

    // 1. 提交视频生成任务
    const generationResult = await generateVideo(prompt);
    const taskId = generationResult.id;
    console.log('📋 任务ID:', taskId);

    // 2. 轮询查询结果
    console.log('🔍 开始查询生成结果...');
    const result = await pollVideoResult(taskId);

    if (result) {
      console.log('✅ 视频生成流程完成！');
      return result;
    } else {
      console.log('❌ 视频生成失败或超时');
      return null;
    }
  } catch (error) {
    console.error('❌ 视频生成流程失败:', JSON.stringify(error));
    return null;
  }
}

// 测试函数
export async function testVideoGeneration(
  object
): Promise<VideoResultItem[] | null> {
  console.log('🧪 开始测试视频生成...\n');

  // 测试生成新视频
  const result = await generateVideoComplete(object);

  if (result) {
    console.log('\n🎬 生成的视频信息:');
    console.log('视频链接:', JSON.stringify(result[0].url));
    console.log('封面链接:', JSON.stringify(result[0].cover_image_url));
    console.log('完整链接返回对象' + JSON.stringify(result));
    return result;
  }
}

interface resultType {
  cover_image_url: string;
  url: string;
}
// 定义请求配置类型
interface RequestConfig {
  baseURL: string;
  timeout: number;
  headers: {
    'Content-Type': string;
    Authorization: string;
  };
}

// 定义视频生成请求参数类型
interface VideoGenerationRequest {
  model: string;
  prompt: string;
  user_id: string;
}

// 定义视频生成响应数据类型
interface VideoGenerationResponse {
  id: string;
  [key: string]: any;
}

// 定义视频结果项类型
interface VideoResultItem  extends MediaResultItem{
  cover_image_url: string;
  url: string;
}

// 定义任务状态类型
type TaskStatus = 'SUCCESS' | 'FAILED' | 'PROCESSING' | 'PENDING';

// 定义视频结果响应数据类型
interface VideoResultResponse {
  model: string;
  request_id: string;
  task_status: TaskStatus;
  video_result: VideoResultItem[];
}
// 修正图片结果类型（与API返回对齐）
interface ImageResultResponse {
  model: string;
  request_id: string;
  task_status: TaskStatus;
  image_result: {
    url: string; // 后端返回的图片URL
  }[];
}

// 图片生成结果类型（与视频统一结构，方便复用）
interface MediaResultItem {
  url: string;          // 资源URL（图片/视频）
  cover_image_url?: string; // 封面（视频特有，图片可复用url）
}

// 定义完整响应数据类型
interface ApiResponse {
  data: VideoResultResponse;
  status: number;
  statusText: string;
  headers: {
    'content-encoding'?: string;
    'content-type'?: string;
    date?: string;
    'strict-transport-security'?: string;
    vary?: string;
    'x-log-id'?: string;
    'set-cookie'?: string;
    [key: string]: any;
  };
  config: {
    transitional: {
      silentJSONParsing: boolean;
      forcedJSONParsing: boolean;
      clarifyTimeoutError: boolean;
    };
    adapter: string[];
    transformRequest: (null | any)[];
    transformResponse: (null | any)[];
    timeout: number;
    xsrfCookieName: string;
    xsrfHeaderName: string;
    maxContentLength: number;
    maxBodyLength: number;
    env: {
      Blob: null;
    };
    headers: {
      Accept: string;
      'Content-Type': string;
      Authorization: string;
    };
    baseURL: string;
    method: string;
    url: string;
  };
  request: any;
  performanceTiming: {
    dnsTiming: number;
    firstReceiveTiming: number;
    firstSendTiming: number;
    redirectTiming: number;
    responseBodyTiming: number;
    responseHeaderTiming: number;
    tcpTiming: number;
    tlsTiming: number;
    totalFinishTiming: number;
    totalTiming: number;
  };
}
